package com.util.resttemplateutil;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URI;

public class RestUtils {
    private static final RestTemplate restTemplate = new RestTemplate();

    public static <T> T  get(String url, Class<T> responseType){
        URI uri = URI.create(url);
        restTemplate.setRequestFactory(getFactory());
        return restTemplate.getForObject(uri, responseType);
    }

    public static <T> T post(String url, Object request, Class<T> responseType){
        restTemplate.setRequestFactory(getFactory());
        URI uri = URI.create(url);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> httpEntity = new HttpEntity<>(request, headers);
        return restTemplate.postForObject(uri, httpEntity, responseType);
    }

    public static SimpleClientHttpRequestFactory getFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        // 代理的url网址或ip, port端口
        InetSocketAddress address = new InetSocketAddress("proxy.market.pt.xiaomi.com", 9443);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
        factory.setProxy(proxy);
        return factory;
    }
}
